package model

import (
	myConfig "common/config"
	"common/helper"
	myredis "common/redis"
	myUserHelp "common/userHelp"
	"database/sql"
	"errors"
	"fmt"
	"github.com/doug-martin/goqu/v9/exp"
	"strconv"
	"strings"
	"time"

	g "github.com/doug-martin/goqu/v9"
	"github.com/shopspring/decimal"

	"github.com/valyala/fasthttp"
)

type TblDeposit struct {
	Id            string  `json:"id" db:"id" cbor:"id"`
	Oid           string  `json:"oid" db:"oid" cbor:"oid"`
	Uid           string  `json:"uid" db:"uid" cbor:"uid"`
	ParentId      string  `json:"parent_id" db:"parent_id" cbor:"parent_id"`
	Fid           string  `json:"fid" db:"fid" cbor:"fid"`
	Fname         string  `json:"fname" db:"fname" cbor:"fname"`
	Amount        string  `json:"amount" db:"amount" cbor:"amount"`
	State         int     `json:"state" db:"state" cbor:"state"`
	CreatedAt     int64   `json:"created_at" db:"created_at" cbor:"created_at"`
	ConfirmAt     int64   `json:"confirm_at" db:"confirm_at" cbor:"confirm_at"`
	ConfirmUid    string  `json:"confirm_uid" db:"confirm_uid" cbor:"confirm_uid"`
	ConfirmName   string  `json:"confirm_name" db:"confirm_name" cbor:"confirm_name"`
	ReviewRemark  string  `json:"review_remark" db:"review_remark" cbor:"review_remark"`
	Discount      float64 `json:"discount" db:"discount" cbor:"discount"`
	IsFirst       int     `json:"is_first" db:"is_first"`
	IsReceived    int     `json:"is_received" db:"is_received"`
	Hidden        int     `json:"hidden" db:"hidden"`
	Hidden_amount float64 `json:"hidden_amount" db:"hidden_amount"`
}

// 存入数据库
func insertDeposit(record TblDeposit) error {

	query, _, _ := dialect.Insert("tbl_deposit").Rows(record).ToSQL()
	myredis.UpdateSqlFieldToRedis(query)
	return nil
}

func DepositCallBack(fctx *fasthttp.RequestCtx) {

	data := EpayCallBack{}
	// 获取并校验回调参数
	payment := &thirdEpay{}
	data, err := payment.DepositCallBack(fctx)
	helper.InfoLog("depositReq:%s,\nDepositCallBack:%s", string(fctx.PostBody()), data)
	if err != nil {
		helper.SqlSelectErrLog("depositReq:%s,\nDepositCallBack:%s,\nerror:%s", string(fctx.PostBody()), data, err)
		helper.InfoLog("[DepositCallBack]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	p, err := CachePayFactory("1")
	if err != nil {
		helper.InfoLog("[query tbl_pay_factory]:%s", err.Error())
		return
	}

	//对结果sign验证
	var content string
	content = fmt.Sprintf(`amount=%s&appId=%s&custId=%s&merchantOrderId=%s&order=%s&orderStatus=%s&orderTime=%s&payAmt=%s&key=%s`, data.Amount, data.AppId, data.CustId, data.MerchantOrderId, data.Order, data.OrderStatus, data.OrderTime, data.Amount, p.AppKey)
	sign := strings.ToUpper(helper.MD5Hash(content))
	if data.Sign != sign {
		helper.SqlSelectErrLog("content:%s", content)
		helper.InfoLog("[DepositCallBack data.Sign != sign ]:sign error:old sign=%s, sign=%s ", data.Sign, sign)
		fctx.SetBody([]byte("failed"))
		return
	}

	// 查询订单
	order, err := depositFind(data.MerchantOrderId)
	if err != nil {
		err = fmt.Errorf("query order error: [%v]", err)
		helper.InfoLog("[DepositCallBack:depositFind]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	if order.State == DepositSuccess || order.State == DepositCancelled || order.State == DepositRepairSuccess {
		err = fmt.Errorf("duplicated deposite notify: [%d]", order.State)
		helper.InfoLog("[DepositCallBack:order.State]:%s", err.Error())
		fctx.SetBody([]byte(`success`))
		return
	}

	err = compareAmount(data.Amount, order.Amount, 100)
	if err != nil {
		helper.InfoLog("compare amount error: [err: %v, req: %s, origin: %s]", err, data.Amount, order.Amount)
		helper.InfoLog("[DepositCallBack:compareAmount]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}
	// 修改订单状态
	var state string
	if data.OrderStatus != "01" {
		state = fmt.Sprintf(`%d`, DepositReviewing)
	} else {
		state = fmt.Sprintf(`%d`, DepositSuccess)
	}
	err = depositUpdate(state, order, data.OrderTime)
	if err != nil {
		helper.InfoLog("[DepositCallBack:depositUpdate]:%s", err.Error())
		fctx.SetBody([]byte("failed"))
		return
	}

	fctx.SetBody([]byte("success"))
}

func DepositJeepayCallBack(fctx *fasthttp.RequestCtx) {

	data := EpayCallBack{}
	// 获取并校验回调参数
	payment := &thirdEpay{}
	data, err := payment.DepositJeepayCallBack(fctx)
	helper.InfoLog("depositReq:%s,\nDepositCallBack:%s", string(fctx.PostBody()), data)
	if err != nil {
		helper.SqlSelectErrLog("depositReq:%s,\nDepositCallBack:%s,\nerror:%s", string(fctx.PostBody()), data, err)
		helper.InfoLog("[DepositCallBack]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	// 查询订单
	order, err := depositFind(data.MerchantOrderId)
	if err != nil {
		err = fmt.Errorf("query order error: [%v]", err)
		helper.InfoLog("[DepositCallBack:depositFind]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	// 修改订单状态
	var state string
	if data.OrderStatus != "2" {
		state = fmt.Sprintf(`%d`, DepositReviewing)
	} else {
		state = fmt.Sprintf(`%d`, DepositSuccess)
	}
	err = depositUpdate(state, order, data.OrderTime)
	if err != nil {
		helper.InfoLog("[DepositCallBack:depositUpdate]:%s", err.Error())
		fctx.SetBody([]byte("failed"))
		return
	}

	fctx.SetBody([]byte("success"))
}

func DepositPayU2CCallBack(fctx *fasthttp.RequestCtx) {

	data := PayU2CCallBack{}
	// 获取并校验回调参数
	payment := &thirdEpay{}
	data, err := payment.DepositPayu2cCallBack(fctx)
	fmt.Println("status", data.OrderStatus)
	helper.InfoLog("depositReq:%s,\nDepositPay4zCallBack:%s", string(fctx.PostBody()), data)
	if err != nil {
		helper.SqlSelectErrLog("depositReq:%s,\nDepositPay4zCallBack:%s,\nerror:%s", string(fctx.PostBody()), data, err)
		helper.InfoLog("[DepositPay4zCallBack]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	// 查询订单
	order, err := depositFind(data.MrchantOrderNo)
	if err != nil {
		err = fmt.Errorf("query order error: [%v]", err)
		helper.InfoLog("[DepositPay4zCallBack:depositFind]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	/*
		WAITING_PAY	待支付
		PAYING	支付中
		PAID	支付成功
		PAY_FAILED	支付失败
		REFUND	已退款
	*/

	// 修改订单状态
	var state string
	if data.OrderStatus == "PAID" {
		state = fmt.Sprintf(`%d`, DepositSuccess)
	} else if data.OrderStatus == "PAY_FAILED" || data.OrderStatus == "REFUND" {
		state = fmt.Sprintf(`%d`, DepositCancelled)
	} else {
		state = fmt.Sprintf(`%d`, DepositConfirming)
	}
	err = depositUpdate(state, order, data.UpdateTime)
	if err != nil {
		helper.InfoLog("[DepositPay4zCallBack:depositUpdate]:%s", err.Error())
		fctx.SetBody([]byte("failed"))
		return
	}

	fctx.SetBody([]byte("OK"))
}
func DepositPay4zCallBack(fctx *fasthttp.RequestCtx) {

	data := Pay4zCallBack{}
	// 获取并校验回调参数
	payment := &thirdEpay{}
	data, err := payment.DepositPay4zCallBack(fctx)
	fmt.Println("status", data.OrderStatus)
	helper.InfoLog("depositReq:%s,\nDepositPay4zCallBack:%s", string(fctx.PostBody()), data)
	if err != nil {
		helper.SqlSelectErrLog("depositReq:%s,\nDepositPay4zCallBack:%s,\nerror:%s", string(fctx.PostBody()), data, err)
		helper.InfoLog("[DepositPay4zCallBack]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	// 查询订单
	order, err := depositFind(data.MrchantOrderNo)
	if err != nil {
		err = fmt.Errorf("query order error: [%v]", err)
		helper.InfoLog("[DepositPay4zCallBack:depositFind]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	/*
		WAITING_PAY	待支付
		PAYING	支付中
		PAID	支付成功
		PAY_FAILED	支付失败
		REFUND	已退款
	*/

	// 修改订单状态
	var state string
	if data.OrderStatus == "PAID" {
		state = fmt.Sprintf(`%d`, DepositSuccess)
	} else if data.OrderStatus == "PAY_FAILED" || data.OrderStatus == "REFUND" {
		state = fmt.Sprintf(`%d`, DepositCancelled)
	} else {
		state = fmt.Sprintf(`%d`, DepositConfirming)
	}
	err = depositUpdate(state, order, data.UpdateTime)
	if err != nil {
		helper.InfoLog("[DepositPay4zCallBack:depositUpdate]:%s", err.Error())
		fctx.SetBody([]byte("failed"))
		return
	}

	fctx.SetBody([]byte("OK"))
}
func DepositBetcatpayCallBack(fctx *fasthttp.RequestCtx) {

	data := BetcatCallBack{}
	// 获取并校验回调参数
	payment := &thirdEpay{}
	data, err := payment.DepositBetcatCallBack(fctx)
	fmt.Println("status", data.OrderStatus)
	helper.InfoLog("depositReq:%s,\nDepositCallBack:%s", string(fctx.PostBody()), data)
	if err != nil {
		helper.SqlSelectErrLog("depositReq:%s,\nDepositCallBack:%s,\nerror:%s", string(fctx.PostBody()), data, err)
		helper.InfoLog("[DepositCallBack]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	// 查询订单
	order, err := depositFind(data.MerOrderNo)
	if err != nil {
		err = fmt.Errorf("query order error: [%v]", err)
		helper.InfoLog("[DepositCallBack:depositFind]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	// 修改订单状态
	var state string
	if data.OrderStatus == "2" || data.OrderStatus == "3" {
		state = fmt.Sprintf(`%d`, DepositSuccess)
	} else if data.OrderStatus == "-1" || data.OrderStatus == "-2" || data.OrderStatus == "-3" {
		state = fmt.Sprintf(`%d`, DepositCancelled)
	} else {
		state = fmt.Sprintf(`%d`, DepositConfirming)
	}
	err = depositUpdate(state, order, data.UpdateTime)
	if err != nil {
		helper.InfoLog("[DepositCallBack:depositUpdate]:%s", err.Error())
		fctx.SetBody([]byte("failed"))
		return
	}

	fctx.SetBody([]byte("OK"))
}
func DepositCepayCallBack(fctx *fasthttp.RequestCtx) {

	data := EpayCallBack{}
	// 获取并校验回调参数
	payment := &thirdEpay{}
	data, err := payment.DepositCepayCallBack(fctx)
	fmt.Println("status", data.OrderStatus)
	helper.InfoLog("depositReq:%s,\nDepositCallBack:%s", string(fctx.PostBody()), data)
	if err != nil {
		helper.SqlSelectErrLog("depositReq:%s,\nDepositCallBack:%s,\nerror:%s", string(fctx.PostBody()), data, err)
		helper.InfoLog("[DepositCallBack]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	// 查询订单
	order, err := depositFind(data.MerchantOrderId)
	if err != nil {
		err = fmt.Errorf("query order error: [%v]", err)
		helper.InfoLog("[DepositCallBack:depositFind]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return
	}

	// 修改订单状态
	var state string
	if data.OrderStatus != "1" {
		state = fmt.Sprintf(`%d`, DepositReviewing)
	} else {
		state = fmt.Sprintf(`%d`, DepositSuccess)
	}
	err = depositUpdate(state, order, data.OrderTime)
	if err != nil {
		helper.InfoLog("[DepositCallBack:depositUpdate]:%s", err.Error())
		fctx.SetBody([]byte("failed"))
		return
	}

	fctx.SetBody([]byte("OK"))
}

// 获取订单信息
func depositFind(id string) (TblDeposit, error) {

	d := TblDeposit{}

	ex := g.Ex{"id": id}
	query, _, _ := dialect.From("tbl_deposit").Select(colsDeposit...).Where(ex).Limit(1).ToSQL()
	err := meta.MerchantDB.Get(&d, query)
	if err == sql.ErrNoRows {
		return d, errors.New(helper.OrderNotExist)
	}

	if err != nil {
		return d, pushLog(err, helper.DBErr)
	}

	return d, nil
}

// 金额对比
func compareAmount(compare, compared string, cent int64) error {

	ca, err := decimal.NewFromString(compare)
	if err != nil {
		return errors.New("parse amount error")
	}

	ra, err := decimal.NewFromString(compared)
	if err != nil {
		return errors.New("parse amount error")
	}

	if ca.Cmp(ra.Mul(decimal.NewFromInt(cent))) != 0 {
		return errors.New("invalid amount")
	}

	return nil
}

func depositUpdate(state string, order TblDeposit, payAt string) error {

	// 加锁
	err := depositLock(order.Id)
	if err != nil {
		return err
	}
	defer depositUnLock(order.Id)

	// 充值成功处理订单状态
	if state == fmt.Sprintf(`%d`, DepositSuccess) {
		_ = cacheDepositProcessingRem(order.Uid)
		//err = depositUpPointSuccess(order.Id, order.Uid, "", "", payAt, state)
		err = myUserHelp.DepositUpPointSuccess(order.Id, order.Uid, state)
		if err != nil {
			return err
		}
	} else {
		err = depositUpPointCancel(order.Id, order.Uid, "", "", payAt, state)
		if err != nil {
			return err
		}
	}

	return nil
}

// depositLock 锁定充值订单 防止并发多充钱
func depositLock(id string) error {

	key := fmt.Sprintf(depositOrderLockKey, id)
	return Lock(key)
}

// depositUnLock 解锁充值订单
func depositUnLock(id string) {
	key := fmt.Sprintf(depositOrderLockKey, id)
	Unlock(key)
}

// cacheDepositProcessingRem 清除未未成功的订单计数
func cacheDepositProcessingRem(uid string) error {

	automatic_lock_key := fmt.Sprintf("finance:alock:%s", uid)
	return meta.MerchantRedis.Unlink(ctx, automatic_lock_key).Err()
}

// depositOrderFindOne 查询存款订单
func depositOrderFindOne(ex g.Ex) (TblDeposit, error) {

	order := TblDeposit{}
	query, _, _ := dialect.From("tbl_deposit").Select(colsDeposit...).Where(ex).Limit(1).ToSQL()
	err := meta.MerchantDB.Get(&order, query)
	if err == sql.ErrNoRows {
		return order, errors.New(helper.OrderNotExist)
	}

	if err != nil {
		return order, pushLog(err, helper.DBErr)
	}

	return order, nil
}

// 存款上分
func depositUpPointCancel(did, uid, name, remark, payAt, state string) error {

	// 判断状态是否合法
	allow := map[string]bool{
		fmt.Sprintf(`%d`, DepositReviewing): true,
	}
	if _, ok := allow[state]; !ok {
		return errors.New(helper.OrderStateErr)
	}

	// 判断订单是否存在
	ex := g.Ex{"id": did, "state": DepositConfirming}
	order, err := depositOrderFindOne(ex)
	if err != nil {
		return err
	}

	// 如果已经有一笔订单补单成功,则其他订单不允许补单成功
	if fmt.Sprintf(`%d`, DepositSuccess) == state || fmt.Sprintf(`%d`, DepositRepairSuccess) == state {
		// 这里的ex不能覆盖上面的ex
		//_, err = depositOrderFindOne(g.Ex{"oid": order.Oid, "state": DepositSuccess})
		_, err = depositOrderFindOne(g.Ex{"id": order.Id, "state": []int{DepositSuccess, DepositRepairSuccess}})
		if err != nil && err.Error() != helper.OrderNotExist {
			return err
		}

		if err == nil {
			return errors.New(helper.OrderExist)
		}
	}

	now := time.Now()

	record := g.Record{
		"state":         state,
		"confirm_at":    now.Unix(),
		"confirm_uid":   uid,
		"confirm_name":  name,
		"review_remark": remark,
	}
	query, _, _ := dialect.Update("tbl_deposit").Set(record).Where(ex).ToSQL()
	// 存款失败 直接修改订单状态
	_, err = meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(err, helper.DBErr)
	}

	return nil
}

func depositSuccessCount(uid string) int64 {

	var data sql.NullInt64
	query, _, _ := dialect.From("tbl_deposit").Select(g.COUNT("id")).Where(g.Ex{"uid": uid, "state": DepositSuccess}).Limit(1).ToSQL()
	err := meta.MerchantDB.Get(&data, query)
	if errors.Is(err, sql.ErrNoRows) {
		return 0
	}

	if err != nil {
		return 0
	}

	return data.Int64
}

func depositSuccessAmount(uid string) float64 {

	var data sql.NullFloat64
	query, _, _ := dialect.From("tbl_deposit").Select("amount").Where(g.Ex{"uid": uid, "state": DepositSuccess}).Order(g.C("amount").Desc()).Limit(1).ToSQL()
	err := meta.MerchantDB.Get(&data, query)
	if errors.Is(err, sql.ErrNoRows) {
		return 0
	}

	if err != nil {
		return 0
	}

	return data.Float64
}

func DepositList(fctx *fasthttp.RequestCtx, flag int) ([]UserDepositList, error) {

	var res []UserDepositList
	var list UserDepositList
	var deposit []TblDeposit
	uid := GetUidFromToken(fctx)
	if uid == "" {
		return res, errors.New(helper.AccessTokenExpires)
	}

	now := time.Now()
	var startTime, endTime int64
	switch flag {
	case 1:
		// Yesterday
		startTime = time.Date(now.Year(), now.Month(), now.Day()-1, 0, 0, 0, 0, loc).Unix()
		endTime = time.Date(now.Year(), now.Month(), now.Day()-1, 23, 59, 59, 0, loc).Unix()
	case 2:
		// Today
		startTime = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc).Unix()
		endTime = time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, loc).Unix()
	case 3:
		// Last 7 days
		startTime = time.Date(now.Year(), now.Month(), now.Day()-6, 0, 0, 0, 0, loc).Unix()
		endTime = time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, loc).Unix()
	case 4:
		// Last 15 days
		startTime = time.Date(now.Year(), now.Month(), now.Day()-14, 0, 0, 0, 0, loc).Unix()
		endTime = time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, loc).Unix()
	case 5:
		// Last 30 days
		startTime = time.Date(now.Year(), now.Month(), now.Day()-29, 0, 0, 0, 0, loc).Unix()
		endTime = time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, loc).Unix()
	default:
		// All time
		startTime = 0
		endTime = 0
	}

	ex := g.Ex{"uid": uid, "state": []int{DepositSuccess, DepositRepairSuccess}}
	if startTime != 0 && endTime != 0 {
		if startTime >= endTime {
			return res, errors.New(helper.QueryTimeRangeErr)
		}
		ex["created_at"] = g.Op{"between": exp.NewRangeVal(startTime, endTime)}
	}
	query, _, _ := dialect.From("tbl_deposit").Select(colsDeposit...).Where(ex).ToSQL()
	err := meta.MerchantDB.Select(&deposit, query)
	if err == sql.ErrNoRows {
		return res, errors.New(helper.OrderNotExist)
	}
	if err != nil {
		return res, pushLog(err, helper.DBErr)
	}
	if len(deposit) > 0 {
		for _, i := range deposit {
			amount, err := strconv.ParseFloat(i.Amount, 64)
			if err != nil {
				return res, errors.New(helper.FormatErr)
			}
			list.Id = i.Id
			list.CreatedAt = i.CreatedAt
			list.Amount = amount
			list.Discount = i.Discount
			list.TotAmount = amount + i.Discount
			list.State = i.State
			res = append(res, list)
		}
	}

	return res, nil
}

type UserDepositList struct {
	Id        string  `json:"id" db:"id" cbor:"id"`
	CreatedAt int64   `json:"created_at" db:"created_at" cbor:"created_at"`
	Amount    float64 `json:"amount" db:"amount" cbor:"amount"`
	Discount  float64 `json:"discount" db:"discount" cbor:"discount"`
	TotAmount float64 `json:"tot_amount" db:"tot_amount"`
	State     int     `json:"state" db:"state" cbor:"state"`
}

type UserDepositDiscountList struct {
	Id       string  `json:"id" db:"id"`
	Discount float64 `json:"discount" db:"discount"`
}

func DepositDiscountList(fctx *fasthttp.RequestCtx) (UserDepositDiscountList, error) {

	var res UserDepositDiscountList
	var deposit TblDeposit
	uid := GetUidFromToken(fctx)
	if uid == "" {
		return res, errors.New(helper.AccessTokenExpires)
	}
	ex := g.Ex{"uid": uid, "is_first": 1, "is_received": 0}
	discountCondition := g.C("discount").Gt(0)
	combinedCondition := g.And(ex, discountCondition)
	query, _, _ := dialect.From("tbl_deposit").Select(colsDeposit...).Where(combinedCondition).Limit(1).ToSQL()
	err := meta.MerchantDB.Get(&deposit, query)
	if err == sql.ErrNoRows {
		return res, nil
	}
	if err != nil {
		return res, nil
	}
	res.Id = deposit.Id
	res.Discount = deposit.Discount

	return res, nil
}

func DepositDiscountApply(fctx *fasthttp.RequestCtx, orderId string, discount float64) error {

	uid := GetUidFromToken(fctx)
	if uid == "" {
		return errors.New(helper.AccessTokenExpires)
	}
	myUserHelp.LoadUserToRedis(uid)

	lk := fmt.Sprintf("w:%s", myUserHelp.GetMemberName(uid))
	err := WithLock(lk)
	if err != nil {
		return err
	}
	defer Unlock(lk)

	// 查询订单
	order, err := depositFind(orderId)
	if err != nil {
		err = fmt.Errorf("query order error: [%v]", err)
		helper.InfoLog("[DepositDiscountApply:depositFind]:%s", err.Error())
		fctx.SetBody([]byte(`failed`))
		return err
	}

	if myConfig.GetGameCfgInt(myConfig.CfgDepositBonusManually) == 0 {
		return errors.New(helper.OrderTakenAlready)
	}

	if order.IsReceived == 1 {
		return errors.New(helper.OrderTakenAlready)
	}

	if discount != order.Discount {
		return errors.New(helper.AmountErr)
	}

	if order.Discount > 0 {
		if order.IsFirst == 1 {
			myUserHelp.AddBalanceTransactionRecord(uid, order.Discount, helper.TransactionFirstDepositBonus, "0", helper.GenId(), 0.00, "", "", 0)
			myUserHelp.AddUserWageItem(uid, order.Discount, helper.TransactionFirstDepositBonus)
			myUserHelp.AddUserBalanceByFloat64(uid, order.Discount)
			_, errExec := GetMasterDBInstance().Exec("CALL tbl_report_user_change_update(?,?,?,?)", uid, helper.TransactionFirstDepositBonus, order.Discount, time.Now().Unix())
			if errExec != nil {
				helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_change_update(%s,%d,%0.2f,%d);	reason:%s",
					uid, helper.TransactionFirstDepositBonus, order.Discount, time.Now().Unix(), errExec.Error())
			}
		} else {
			myUserHelp.AddBalanceTransactionRecord(uid, order.Discount, helper.TransactionDepositBonus, "0", helper.GenId(), 0.00, "", "", 0)
			myUserHelp.AddUserWageItem(uid, order.Discount, helper.TransactionDepositBonus)
			myUserHelp.AddUserBalanceByFloat64(uid, order.Discount)
			_, errExec := GetMasterDBInstance().Exec("CALL tbl_report_user_change_update(?,?,?,?)", uid, helper.TransactionDepositBonus, order.Discount, time.Now().Unix())
			if errExec != nil {
				helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_change_update(%s,%d,%0.2f,%d);	reason:%s",
					uid, helper.TransactionDepositBonus, order.Discount, time.Now().Unix(), errExec.Error())
			}
		}
	}
	ex := g.Ex{
		"id": orderId,
	}
	record := g.Record{
		"is_received": 1,
	}

	query, _, _ := dialect.Update("tbl_deposit").Set(record).Where(ex).ToSQL()
	_, errExec := GetMasterDBInstance().Exec(query)
	if errExec != nil {
		helper.SqlErrLog("[DepositDiscountApply:Exec]:update sql: %s reason:%s", query, errExec.Error())
		return errors.New(helper.DBErr)
	}

	return nil
}
